import React, { useState, useContext } from 'react';
import { Table, Input, Form } from 'antd';
import styles from './index.less';

const EditableContext = React.createContext();

const EditableRow = ({ form, index, ...props }) => (
    <EditableContext.Provider value={form}>
        <tr {...props} />
    </EditableContext.Provider>
);
const EditableFormRow = Form.create()(EditableRow);

const EditableCell = ({
    editable,
    dataIndex,
    title,
    record,
    index,
    handleRowSave,
    children,
    editRender,
    rules = null,
    ...restProps
}) => {
    const form = useContext(EditableContext);
    const [editing, setEditing] = useState(true);
    const toggleEdit = () => {
        setEditing(!editing);
    };

    const save = e => {
        form.validateFields((error, values) => {
            // 验证通过的单元格切换状态
            // const cellIsErr = form.getFieldError(dataIndex);
            // if (!cellIsErr) {
            //     toggleEdit();
            // }
            const { extra } = e || {};
            if (error) {
                handleRowSave({ ...record, ...values, isValidatorPass: false, ...extra });
                return;
            }
            handleRowSave({ ...record, ...values, isValidatorPass: true, ...extra });
        });
    };

    const renderCell = () => {
        if (editing) {
            if (editRender) {
                return editRender({ record, form, save, dataIndex, title });
            }
            return (
                <Form.Item style={{ margin: 0 }}>
                    {form.getFieldDecorator(dataIndex, {
                        rules,
                        initialValue: record[dataIndex]
                    })(<Input onPressEnter={save} onBlur={save} placeholder="请输入内容" maxLength={50} />)}
                </Form.Item>
            );
        }
        return (
            <div
                className={styles.editableCellValueWrap}
                onClick={() => {
                    toggleEdit();
                }}
            >
                {children}
            </div>
        );
    };

    return (
        <td {...restProps}>
            {editable ? <EditableContext.Consumer>{renderCell}</EditableContext.Consumer> : children}
        </td>
    );
};

const EditTable = ({ dataSource, columns, handleRowSave, ...rest }) => {
    const components = {
        body: {
            row: EditableFormRow,
            cell: EditableCell
        }
    };

    let newColumns = columns;

    if (columns?.length > 0) {
        newColumns = columns.map(col => {
            if (!col.editable) {
                return col;
            }
            return {
                ...col,
                onCell: record => ({
                    record,
                    rules: col.rules,
                    editRender: col.editRender,
                    editable: col.editable,
                    dataIndex: col.dataIndex,
                    title: col.title,
                    handleRowSave
                })
            };
        });
    }

    return (
        <Table
            style={{ width: '100%' }}
            dataSource={dataSource}
            pagination={false}
            components={components}
            columns={newColumns}
            rowClassName={() => styles.editableRow}
            {...rest}
        />
    );
};

export default EditTable;
